package auction.auction;

import auction.dao.AuctionDao;
import auction.dao.AuctionRecordDao;
import auction.dao.AuctionUserDao;
import auction.entity.Auction;
import auction.entity.Auctionrecord;
import auction.entity.Auctionuser;
import auction.util.MyBatisUtil;
import com.alibaba.fastjson.JSON;
import org.apache.ibatis.session.SqlSession;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.swing.*;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class AuctionAction {

    //用户主页方法：分页查询
    public String home(HttpServletRequest request, HttpServletResponse response){
        SqlSession sqlSession=null;
        try {
            sqlSession= MyBatisUtil.createSqlSession();
            // 获取当前页码
            String pageStr = request.getParameter("page");
            if(pageStr==null){
                pageStr="1";
            }
            int pageNumber = (pageStr != null && !pageStr.isEmpty()) ? Integer.parseInt(pageStr) : 1;
            // 每页显示5条记录
            int pageSize = 5;
            Map<String, Integer> parameters = new HashMap<>();
            parameters.put("pageSize", pageSize);
            //偏移量：如果是第二页那就是  （2-1）*6=6从第六条数据开始查到第10条
            parameters.put("offset", (pageNumber - 1) * pageSize);
            //调用方法
            List<Auction> count = sqlSession.getMapper(AuctionDao.class).selectByPage(parameters);
            //储存数据
            request.setAttribute("count", count);
            // 查询总记录数，用于计算总页数
            int totalCount = sqlSession.getMapper(AuctionDao.class).getTotalCount();
            //总页数
            int totalPages = (int) Math.ceil((double) totalCount / pageSize);
            // 设置前后页码信息
            //点击上一页，当前页数减一，减到0就取1
            int prevPage = Math.max(1, pageNumber - 1);
            //同理
            int nextPage = Math.min(totalPages, pageNumber + 1);
            // 将这些值传递给前端
            request.setAttribute("currentPage", pageNumber);//当前页
            request.setAttribute("prevPage", prevPage);
            request.setAttribute("nextPage", nextPage);
            request.setAttribute("totalPages", totalPages);//总页数
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            MyBatisUtil.closeSqlSession(sqlSession);
        }
        return "/home.jsp";
    }

    //条件查询方法
    public String search(HttpServletRequest request, HttpServletResponse response){
        SqlSession sqlSession=null;
        try {
            sqlSession= MyBatisUtil.createSqlSession();
            // 获取当前页码，默认为1
            String pageStr = request.getParameter("page");
            if(pageStr==null){
                pageStr="1";
            }
            //当前页面数
            int pageNumber = (pageStr != null && !pageStr.isEmpty()) ? Integer.parseInt(pageStr) : 1;
            int pageSize = 5; // 每页显示5条记录
            //给条件put值
            Map<String, Integer> parameters = new HashMap<>();
            parameters.put("pageSize", pageSize);
            parameters.put("offset", (pageNumber - 1) * pageSize);
            Auction auction = new Auction();
            //获取参数
            String name = request.getParameter("name");
            String desc = request.getParameter("desc");
            String start = request.getParameter("start");
            String end = request.getParameter("end");
            String priceStr = request.getParameter("price");
            // 定义日期格式
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            dateFormat.setLenient(false); // 设置为非宽松模式，这样不符合格式的日期将抛出异常
            Date startDate = null;
            Date endDate = null;
            try {
                // 设置拍卖名称和描述
                auction.setAuctionname(name);
                auction.setAuctiondesc(desc);
                // 解析开始日期
                if (start != null && !start.isEmpty()) {
                    startDate = dateFormat.parse(start);
                }
                // 解析结束日期
                if (end != null && !end.isEmpty()) {
                    endDate = dateFormat.parse(end);
                }
                // 设置拍卖的开始和结束时间
                auction.setAuctionstarttime(startDate);
                auction.setAuctionendtime(endDate);
                // 解析价格
                if (priceStr != null && !priceStr.isEmpty()) {
                    try {
                        BigDecimal price = new BigDecimal(priceStr);
                        auction.setAuctionstartprice(price);
                    } catch (NumberFormatException e) {
                        // 价格转换失败，记录日志或抛出自定义异常
                        // 例如：throw new IllegalArgumentException("价格格式不正确");
                    }
                }
            } catch (ParseException e) {
                // 日期解析异常，记录日志或返回错误信息给用户
                // 例如：e.printStackTrace(); 或 throw new ServletException("日期解析错误", e);
            }
            List<Auction> count = sqlSession.getMapper(AuctionDao.class).selectByCondition(auction,parameters);
            request.setAttribute("count", count);
            // 查询总记录数，用于计算总页数
            int totalCount = sqlSession.getMapper(AuctionDao.class).getTotalCount();
            int totalPages = (int) Math.ceil((double) totalCount / pageSize);
            // 设置前后页码信息
            int prevPage = Math.max(1, pageNumber - 1);
            int nextPage = Math.min(totalPages, pageNumber + 1);
            // 将这些值传递给前端
            request.setAttribute("currentPage", pageNumber);
            request.setAttribute("prevPage", prevPage);
            request.setAttribute("nextPage", nextPage);
            request.setAttribute("totalPages", totalPages);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            MyBatisUtil.closeSqlSession(sqlSession);
        }
        return "/home.jsp";
    }

    //竞拍页面
    public String auction(HttpServletRequest request,HttpServletResponse response){
        //获取商品id
        String id = request.getParameter("id");
        SqlSession sqlSession=null;
        try {
            //查询商品信息
            sqlSession= MyBatisUtil.createSqlSession();
            Auction count = sqlSession.getMapper(AuctionDao.class).selectAuctionById(Integer.parseInt(id));
            request.setAttribute("count",count);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            MyBatisUtil.closeSqlSession(sqlSession);
        }
        try {
            sqlSession= MyBatisUtil.createSqlSession();
            //查询商品出价记录
            List<Auctionrecord> count2 = sqlSession.getMapper(AuctionRecordDao.class).getAuctionRecordsWithUserDetails(Integer.parseInt(id));
            request.setAttribute("count2",count2);
            for (Auctionrecord auctionrecord : count2) {
                List<Auctionuser> auctionuser = auctionrecord.getAuctionuser();
                request.setAttribute("user",auctionuser);
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            MyBatisUtil.closeSqlSession(sqlSession);
        }
        return "/auction.jsp";
    }
    //点击的竞拍方法
    public String auctionResult(HttpServletRequest request,HttpServletResponse response){
        SqlSession sqlSession=null;
        Auctionrecord record =new Auctionrecord();
        try {
            sqlSession= MyBatisUtil.createSqlSession();
            //获取用户id
            //根据用户名获取用户id
            HttpSession session=request.getSession();
            String username = (String) session.getAttribute("username");
            int id = sqlSession.getMapper(AuctionUserDao.class).getUserIdByName(username);
            // 获取当前的LocalDateTime
            LocalDateTime now = LocalDateTime.now();
            // 使用DateTimeFormatter来格式化LocalDateTime为字符串
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            String formattedDateTime = now.format(formatter);
            // 如果你确实需要将这个字符串转换回Date对象，你可以这样做
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            try {
                Date auctionTime = sdf.parse(formattedDateTime);
                // 然后你可以设置这个Date对象到record中
                record.setAuctiontime(auctionTime);
            } catch (java.text.ParseException e) {
                e.printStackTrace();
            }
            //获取商品id
            String auctionId =request.getParameter("auctionid");
            //获取价格和现在的最大价格进行比价
            String price = request.getParameter("price");
            //获取商品以前是是第一次竞拍如果是就不用进行和最大出售价格进行比较
            //获取商品的起拍价
            String startPrice =request.getParameter("startPrice");
            System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
            if(Double.parseDouble(startPrice)>Double.parseDouble(price)){
                JOptionPane.showMessageDialog(null, "竞拍失败，价格不能低于最大竞拍价格", "提示", JOptionPane.INFORMATION_MESSAGE);
                return "/do/auction/home";
            }
            int isHaving = sqlSession.getMapper(AuctionRecordDao.class).isHavingAuctionRecord(Integer.parseInt(auctionId));
            if(isHaving>0){
                int maxMin = sqlSession.getMapper(AuctionRecordDao.class).selectMatSalePrice(Integer.valueOf(auctionId));
                if(Integer.parseInt(price)<maxMin){
                    JOptionPane.showMessageDialog(null, "竞拍失败，价格不能低于最大竞拍价格", "提示", JOptionPane.INFORMATION_MESSAGE);
                    return "/do/auction/home";
                }
            }
            record.setUserid((long) id);
            record.setAuctionid(Long.valueOf(auctionId));
            record.setAuctionprice(BigDecimal.valueOf(Long.parseLong(price)));
            int count = sqlSession.getMapper(AuctionRecordDao.class).insertAuctionRecord(record);
            if(count>0){
                JOptionPane.showMessageDialog(null, "竞拍成功", "提示", JOptionPane.INFORMATION_MESSAGE);
                return "/do/auction/doAuctionResult";
            }else {
                JOptionPane.showMessageDialog(null, "竞拍失败，请联系管理员", "提示", JOptionPane.INFORMATION_MESSAGE);
                return "/auction.jsp";
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            MyBatisUtil.closeSqlSession(sqlSession);
        }
        return "/auctionResult.jsp";
    }
    //查看商品结束拍卖和商品正在拍卖的商品
    public  String doAuctionResult(HttpServletRequest request,HttpServletResponse response){
        //查询拍卖结束的商品
        SqlSession sqlSession=null;
        try {
            sqlSession= MyBatisUtil.createSqlSession();
            List<Auction> count = sqlSession.getMapper(AuctionDao.class).slelectEndAuctions();
           request.setAttribute("count",count);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            MyBatisUtil.closeSqlSession(sqlSession);
        }
        //查询拍卖中的商品

        try {
            sqlSession= MyBatisUtil.createSqlSession();
            List<Auction> count2 = sqlSession.getMapper(AuctionDao.class).slelectLiveAuctions();
            // 使用for-each循环遍历List

            request.setAttribute("count2",count2);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            MyBatisUtil.closeSqlSession(sqlSession);
        }

        return "/auctionResult.jsp";
    }


    //管理员主页
    public String homeAdmin(HttpServletRequest request,HttpServletResponse response){
        System.out.println("admin");
        SqlSession sqlSession=null;
        try {
            sqlSession= MyBatisUtil.createSqlSession();
            // 获取当前页码，默认为1
            String pageStr = request.getParameter("page");
            if(pageStr==null){
                pageStr="1";
            }
            int pageNumber = (pageStr != null && !pageStr.isEmpty()) ? Integer.parseInt(pageStr) : 1;
            int pageSize = 5; // 每页显示5条记录
            Map<String, Integer> parameters = new HashMap<>();
            parameters.put("pageSize", pageSize);
            parameters.put("offset", (pageNumber - 1) * pageSize);
            List<Auction> count = sqlSession.getMapper(AuctionDao.class).selectByPage(parameters);
            request.setAttribute("count", count);
            // 查询总记录数，用于计算总页数
            int totalCount = sqlSession.getMapper(AuctionDao.class).getTotalCount();
            int totalPages = (int) Math.ceil((double) totalCount / pageSize);
            // 设置前后页码信息
            int prevPage = Math.max(1, pageNumber - 1);
            int nextPage = Math.min(totalPages, pageNumber + 1);
            // 将这些值传递给前端
            request.setAttribute("currentPage", pageNumber);
            request.setAttribute("prevPage", prevPage);
            request.setAttribute("nextPage", nextPage);
            request.setAttribute("totalPages", totalPages);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            MyBatisUtil.closeSqlSession(sqlSession);
        }
        return "/homeAdmin.jsp";
    }

    //删除商品
    public  String delete(HttpServletRequest request, HttpServletResponse response){
        //获取商品id
        String id= request.getParameter("id");
        SqlSession sqlSession=null;
        try {
            PrintWriter out = response.getWriter();
            sqlSession= MyBatisUtil.createSqlSession();
            int count = sqlSession.getMapper(AuctionDao.class).deleteAuctionById(Integer.parseInt(id));
            out.print(JSON.toJSONString(count));
            out.flush();
            out.close();
            response.setStatus(HttpServletResponse.SC_OK);
        }catch (Exception e){
            e.printStackTrace();
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }finally {
            MyBatisUtil.closeSqlSession(sqlSession);
        }
        return "/homeAdmin.jsp";
    }
    //修改商品的展示属性方法
    public  String update(HttpServletRequest request ,HttpServletResponse response){
        String auction = request.getParameter("auctionid");
        SqlSession sqlSession=null;
        try {
            sqlSession= MyBatisUtil.createSqlSession();
            Auction count = sqlSession.getMapper(AuctionDao.class).selectAuctionById(Integer.valueOf(auction));
            request.setAttribute("count",count);
            System.out.println(count);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            MyBatisUtil.closeSqlSession(sqlSession);
        }
        return "/updateAuction.jsp";
    }

    public String doupdate(HttpServletRequest request ,HttpServletResponse response){
        String username = request.getParameter("username");
        String startPrice = request.getParameter("startPrice");
        String bottomPrice = request.getParameter("bottomPrice");
        String startTime = request.getParameter("startTime");
        String endTime = request.getParameter("endTime");
        String desc = request.getParameter("desc");
        String img = request.getParameter("img");
        String id = request.getParameter("id");
        // 创建 Auction 对象并设置属性
        Auction auction = new Auction();
        // 添加非空判断，如果参数不为空，则设置对应的属性
        if (username != null&&!username.isEmpty()) {
            auction.setAuctionname(username);
        }
        if (startPrice != null&&!startPrice.isEmpty()) {
            auction.setAuctionstartprice(BigDecimal.valueOf(Double.parseDouble(startPrice)));
        }
        if (bottomPrice != null&&!bottomPrice.isEmpty()) {
            auction.setAuctionupset(BigDecimal.valueOf(Double.parseDouble(bottomPrice)));
        }
        if (startTime != null&&!startTime.isEmpty()) {
            // 需要将字符串转换为日期类型，这里假设日期字符串的格式为 "yyyy-MM-dd HH:mm:ss"
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            try {
                Date startDate = sdf.parse(startTime);
                auction.setAuctionstarttime(startDate);
            } catch (ParseException e) {
                e.printStackTrace();
                // 处理日期格式转换异常
            }
        }
        if (endTime != null&&!endTime.isEmpty()) {
            // 同样的方式转换为日期类型，并设置结束时间
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            try {
                Date startDate = sdf.parse(endTime);
                auction.setAuctionstarttime(startDate);
            } catch (ParseException e) {
                e.printStackTrace();
                // 处理日期格式转换异常
            }

        }
        if (desc != null&&!desc.isEmpty()) {
            auction.setAuctiondesc(desc);
        }
        if (img != null&&!img.isEmpty()) {
            auction.setAuctionpic(img);
        }
        if (id != null&&!id.isEmpty()) {
            // 这里假设拍卖品编号是整型
            auction.setAuctionid(Long.parseLong(id));
        }
        SqlSession sqlSession=null;
        try {
            sqlSession= MyBatisUtil.createSqlSession();
            int count = sqlSession.getMapper(AuctionDao.class).updateAuctionById(auction);
            System.out.println(count);
            if(count>0){
                JOptionPane.showMessageDialog(null, "修改成功", "提示", JOptionPane.INFORMATION_MESSAGE);
                return "/do/auction/homeAdmin";
            }else {
                JOptionPane.showMessageDialog(null, "修改成功", "提示", JOptionPane.INFORMATION_MESSAGE);
                return "";
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            MyBatisUtil.closeSqlSession(sqlSession);
        }
        // 创建一个弹窗，标题为"弹窗标题"，消息为"这是弹窗的消息"
        return "/do/auction/homeAdmin";
    }
    //添加页面
    public String addAuction(HttpServletRequest request, HttpServletResponse response){
        return "/addAuction.jsp";
    }
    public String doAddAuction(HttpServletRequest request, HttpServletResponse response){
        String username = request.getParameter("username");
        String startPrice = request.getParameter("startPrice");
        String bottomPrice = request.getParameter("bottomPrice");
        String startTime = request.getParameter("startTime");
        String endTime = request.getParameter("endTime");
        String img = request.getParameter("img");
        String description = request.getParameter("description");
        SqlSession sqlSession=null;
        try {
            sqlSession= MyBatisUtil.createSqlSession();
            Auction auction =new Auction();
            // 非空验证并设置拍卖品名称
            if (username != null && !username.isEmpty()) {
                auction.setAuctionname(username);
            }
            // 非空验证并设置起拍价
            if (startPrice != null && !startPrice.isEmpty()) {
                auction.setAuctionstartprice(BigDecimal.valueOf(Double.parseDouble(startPrice)));
            }
            // 非空验证并设置底价
            if (bottomPrice != null && !bottomPrice.isEmpty()) {
                auction.setAuctionupset(BigDecimal.valueOf(Double.parseDouble(bottomPrice)));
            }
            // 非空验证并设置开始时间
            if (startTime != null && !startTime.isEmpty()) {
                try {
                    // 定义日期格式
                    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    // 将字符串转换为Date对象
                    Date startDate = dateFormat.parse(startTime);
                    auction.setAuctionstarttime(startDate);
                } catch (ParseException e) {
                    // 处理日期格式错误的情况
                    e.printStackTrace();
                }
            }
            // 非空验证并设置结束时间
            if (endTime != null && !endTime.isEmpty()) {
                try {
                    // 定义日期格式
                    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    // 将字符串转换为Date对象
                    Date endDate = dateFormat.parse(endTime);
                    auction.setAuctionendtime(endDate);
                } catch (ParseException e) {
                    // 处理日期格式错误的情况
                    e.printStackTrace();
                }
            }
            // 非空验证并设置图片路径
            if (img != null && !img.isEmpty()) {
                auction.setAuctionpic(img);
            }
            // 同样的方式对其他属性进行非空验证和设置
            int lastIndex = img.lastIndexOf('.');
            // 判断是否找到了'.'，并且保证'.'不在字符串的最后一位
            if (lastIndex != -1 && lastIndex < img.length() - 1) {
                // 截取后缀
                String extension = img.substring(lastIndex + 1);
                auction.setAuctionpictype(extension);
            }
            if(description!=null&&!description.isEmpty()){
                auction.setAuctiondesc(description);
            }
            int count = sqlSession.getMapper(AuctionDao.class).addAuction(auction);
            if(count>0){
                JOptionPane.showMessageDialog(null, "添加成功", "提示", JOptionPane.INFORMATION_MESSAGE);
            }else {
                JOptionPane.showMessageDialog(null, "添加失败", "提示", JOptionPane.INFORMATION_MESSAGE);
            }
            System.out.println(count);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            MyBatisUtil.closeSqlSession(sqlSession);
        }
        return "redirect:/do/auction/homeAdmin";
    }



}
